<!--
 * @Descripttion: 
 * @version: 
 * @Author: 尹鹏孝
 * @Date: 2021-12-10 09:46:51
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2021-12-10 09:55:25
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>n叉树的层序遍历</title>
</head>

<body>
    <script>
        // 给定一个n叉树，返回其节点值的层序遍历（从中向右，逐层遍历）
        // 思路：一个节点有多个孩子的遍历
        class Node {
            constructor(root, left, right) {
                this.root = root;
                this.left = left;
                this.right = right;
            }
            levelOrder(root) {
                // 每个层次，和结果集
                let res = [], queue = [];
                queue.push(root);
                while (queue.length && root !== null) {
                    // 记录节点层数
                    let length = queue.length;
                    // 存放节点层次
                    let curLevel = [];
                    while (length--) {
                        let node = queue.length;
                        curLevel.push(node.root);
                        // 遍历层次不再是left，right
                        for (let item of node.children) {
                            item && queue.push(item);
                        }
                    }
                    res.push(curLevel);
                }

                return res;
            }
        }
    </script>

</body>

</html>